<?php

namespace app\shop\controller\product;

use think\Controller;

class Team extends Controller
{
    protected $TeamOrderModel = null;
    protected $TeamOrderBusinessModel = null;
    protected $BusinessModel = null;
    protected $ProductModel = null;
    protected $RelationModel = null;
    protected $RecordModel = null;

    public function __construct()
    {
        parent::__construct();

        $this->TeamOrderModel = model('product.team.Order');
        $this->TeamOrderBusinessModel = model('product.team.Business');
        $this->BusinessModel = model('business.Business');
        $this->ProductModel = model('product.Product');
        $this->RelationModel = model('product.attribute.Relation');
        $this->RecordModel = model('business.Record');
    }

    //查看拼团数据
    public function index()
    {
        if ($this->request->isPost()) {
            $proid = $this->request->param('proid', 0, 'trim');
            $page = $this->request->param('page', 1, 'trim');
            $keyword = $this->request->param('keyword', '', 'trim');

            // 定义条件数组
            $where = [
                'order.status' => '1'
            ];

            if ($proid) {
                $where['proid'] = $proid;
            }

            if ($keyword) {
                $where['products.name'] = ['LIKE', "%$keyword%"];
            }

            $list = $this->TeamOrderModel->with(['products'])->where($where)->page($page, 10)->order('createtime desc')->select();

            $count = $this->TeamOrderModel->with(['products'])->count();

            $data = [
                'list' => $list,
                'count' => $count
            ];

            if ($list) {
                $this->success('查询拼团数据成功', null, $data);
            } else {
                $this->error('暂无拼团', null, $data);
            }
        }
    }

    //创建拼团
    public function add()
    {
        if ($this->request->isPost()) {
            $busid = $this->request->param('busid', 0, 'trim');
            $proid = $this->request->param('proid', 0, 'trim');
            $teamid = $this->request->param('teamid', 0, 'trim');
            $addrid = $this->request->param('addrid', 0, 'trim');
            $pay = $this->request->param('pay', 'money', 'trim');
            $relationids = $this->request->param('relationids', '', 'trim');
            $remark = $this->request->param('remark', '', 'trim');

            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
            }

            $team = $this->TeamOrderModel->find($teamid);

            if (!$team) {
                $this->error('该拼团记录不存在');
            }

            if ($team['status'] != 1) {
                $this->error('拼团已结束');
            }

            // 参团人数
            $TeamOrderBusinessCount = $this->TeamOrderBusinessModel->where(['teamid' => $teamid])->count();

            if ($TeamOrderBusinessCount >= $team['total']) {
                $this->error('参团人数已满');
            }

            // 是否重复参团
            $TeamOrderBusiness = $this->TeamOrderBusinessModel->where(['teamid' => $teamid, 'busid' => $busid])->find();

            if ($TeamOrderBusiness) {
                $this->error('请勿重复参团');
            }

            $product = $this->ProductModel->where(['status' => '1'])->find($proid);

            if (!$product) {
                $this->error('商品不存在');
            }

            if ($product['stock'] <= 0) {
                $this->error('库存不足');
            }

            $address = model('business.Address')->find($addrid);

            if (!$address) {
                $this->error('收货地址不存在');
            }

            if ($team['proid'] != $proid) {
                $this->error('拼团商品不相同');
            }

            $total = $product['team'];
            $attrs = [];

            $relation = $this->RelationModel->with(['attribute'])->whereIn('relation.id', $relationids)->select();

            if ($relation) {
                foreach ($relation as $item) {
                    $attrs[] = [
                        'title' => $item['attribute']['name'] ?? '未知属性',
                        'value' => $item['value'],
                        'price' => $item['price']
                    ];

                    $total = (float)bcadd($total, $item['price'], 2);
                }
            }

            if ($pay === 'money') {
                /* 
                    新增一条参团名单记录
                    更新用户余额
                    新增消费记录
                */

                // 开启事务
                $this->TeamOrderBusinessModel->startTrans();
                $this->BusinessModel->startTrans();
                $this->RecordModel->startTrans();

                $UpdateMoney = bcsub($business['money'], $total, 2);

                if ($UpdateMoney < 0) {
                    $this->error('余额不足，请及时充值');
                }

                // 组装拼团参团名单
                $TeamOrderBusinessData = [
                    'busid' => $busid,
                    'teamid' => $teamid,
                    'proid' => $proid,
                    'addrid' => $addrid,
                    'total' => $total,
                    'remark' => $remark,
                    'attrs' => $attrs ? json_encode($attrs) : null
                ];

                $TeamOrderBusinessStatus = $this->TeamOrderBusinessModel->validate('common/product/team/Business')->save($TeamOrderBusinessData);

                if ($TeamOrderBusinessStatus === false) {
                    $this->error($this->TeamOrderBusinessModel->getError());
                }

                // 用户余额
                $BusinessData = [
                    'id' => $busid,
                    'money' => $UpdateMoney
                ];

                $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($BusinessData);

                if ($BusinessStatus === false) {
                    $this->TeamOrderBusinessModel->rollback();
                    $this->error('更新用户余额失败');
                }

                // 消费记录
                $RecordData = [
                    'busid' => $busid,
                    'total' => "-{$total}",
                    'content' => "参与【{$product['name']}】商品的拼团，消费了{$total}元"
                ];

                $RecordStatus = $this->RecordModel->validate('common/business/Record')->save($RecordData);

                if ($RecordStatus === false) {
                    $this->TeamOrderBusinessModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->error($this->RecordModel->getError());
                }

                if ($TeamOrderBusinessStatus === false || $BusinessStatus === false || $RecordStatus === false) {
                    $this->TeamOrderBusinessModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->RecordModel->rollback();
                    $this->error('参与拼团失败');
                } else {
                    $this->TeamOrderBusinessModel->commit();
                    $this->BusinessModel->commit();
                    $this->RecordModel->commit();
                    $this->success('参与拼团成功');
                }
            }
        }
    }

    // 获取拼团详情
    public function confirm()
    {
        if ($this->request->isPost()) {
            $busid = $this->request->param('busid', 0, 'trim');
            $teamid = $this->request->param('teamid', 0, 'trim');
            $relationids = $this->request->param('relationids', '', 'trim');

            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
            }

            $team = $this->TeamOrderModel->where(['status' => '1'])->find($teamid);

            if (!$team) {
                $this->error('该拼团不存在');
            }

            $product = $this->ProductModel->where(['status' => '1'])->find($team['proid']);

            if (!$product) {
                $this->error('商品不存在');
            }

            $relation = $this->RelationModel->where(['id' => ['IN', $relationids]])->select();

            $data = [
                'product' => $product,
                'relation' => $relation
            ];

            $this->success('查询确认拼团数据成功', null, $data);
        }
    }

    //查询拼团详情
    public function info()
    {
        if ($this->request->isPost()) {
            $teamid = $this->request->param('teamid', 0, 'trim');
        }

        $team = $this->TeamOrderModel->with(['products'])->where(['order.status' => '1'])->find($teamid);

        if (!$team) {
            $this->error('该拼团不存在');
        }

        $list = $this->TeamOrderBusinessModel->with(['businesss'])->where(['teamid' => $teamid])->select();

        $data = [
            'team' => $team,
            'list' => $list
        ];

        if ($list) {

            $this->success('查询拼团详情成功', null, $data);
        } else {
            $this->error("查询拼团详情失败");
        }
    }
}
